﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using Modbus.Device;

namespace 上位机开发入门程序2
{
    public partial class Form1 : Form
    {
        SerialPort serialPort;
        ModbusSerialMaster master;

        /// <summary>
        /// 初始化串口，并开启，默认连接COM1
        /// </summary>
        private void InitSerial()
        {
            serialPort = new SerialPort();
            serialPort.PortName = "COM1";
            serialPort.BaudRate = 4800;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;
            serialPort.Parity = Parity.Even;
            master = ModbusSerialMaster.CreateRtu(serialPort);
            master.Transport.ReadTimeout = 2000;
            master.Transport.Retries = 10;
            master.Transport.WriteTimeout = 2000;
            serialPort.Open();
        }

        public Form1()
        {
            InitializeComponent();

            InitSerial();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// 从串口中读取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear(); 
            byte slaveNum = 1;   // 从设备的编号
            ushort addrNum = 10; // 开始地址
            byte len = 10;       // 读取多少个数

            Task.Run(() =>
            {
                ushort[] recv = master.ReadHoldingRegisters(slaveNum, addrNum, len);
                foreach (ushort rec in recv)
                {
                    listBox1.Items.Add(rec);
                }
                textBox1.Text = recv[0] + "";
            });
        }

        /// <summary>
        /// 修改第二个位置的值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //string text1 = textBox1.Text;

            string text2 = textBox2.Text;
            string text3 = textBox3.Text;
            string text4 = textBox4.Text;
            
            byte slaveNum = Convert.ToByte(text2);// 从设备的编号
            ushort addrNum = Convert.ToByte(text3);// 开始地址
            ushort value = Convert.ToByte(text4);
            master.WriteSingleRegister(slaveNum, addrNum, value);

            MessageBox.Show("写入成功");
        }
    }
}
